package casa.depesos.app.com.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.text.TextUtils;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;

import com.bumptech.glide.Glide;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import casa.depesos.app.com.BuildConfig;
import casa.depesos.app.com.R;
import casa.depesos.app.com.databinding.ActivityFaceBinding;
import casa.depesos.app.com.dlg.BaseDialogFragment;
import casa.depesos.app.com.dlg.FaceTipDlg;
import casa.depesos.app.com.http.ReqCallback;
import casa.depesos.app.com.http.bean.BankCardBean;
import casa.depesos.app.com.http.bean.GetCodeBean;
import casa.depesos.app.com.http.data.UploadType;
import casa.depesos.app.com.http.req.BankCardReq;
import casa.depesos.app.com.http.req.UploadReq;
import casa.depesos.app.com.utils.Constant;
import casa.depesos.app.com.utils.Report;
import casa.depesos.app.com.utils.Utils;

public class FaceActivity extends BaseActivity {

    ActivityFaceBinding binding;
    ArrayList<String> paths = new ArrayList<>();
    boolean showTip = false;

    @Override
    protected boolean needPadding() {
        return false;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityFaceBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        binding.top.top.setPadding(0, Utils.getStatusBarHeight(this), 0, 0);
        binding.top.title.setText("Verificación facial");

        binding.top.back.setOnClickListener(v -> dealBack());

        binding.next.setOnClickListener(v -> {
            submit(true);
        });

        Report.show("ACTION_MM_001");
    }

    @Override
    protected boolean needKeep() {
        return true;
    }

    private boolean hasCameraPermission() {
        return Utils.hasPermission(this, Permission.CAMERA);
    }

    private void jump() {
        if (!showTip) {
            Report.show("ACTION_MM_004");
            new FaceTipDlg().setOnDismissListener(new BaseDialogFragment.OnDismissListener() {
                @Override
                public void onDismiss(boolean isOk, Object value) {
                    Report.click("ACTION_MM_005");
                    showTip = true;
                    toCamera();
                }
            }).show(getSupportFragmentManager(), "");
        } else {
            toCamera();
        }
    }

    private void toCamera() {
        String[] per;
        if (Constant.white) {
            per = new String[]{Permission.CAMERA};
        } else {
            per = new String[]{Permission.CAMERA, Permission.READ_SMS, Permission.RECEIVE_SMS, Permission.ACCESS_COARSE_LOCATION, Permission.READ_PHONE_STATE};
        }
        XXPermissions.with(this).permission(per).request(new OnPermissionCallback() {
            boolean deal = false;

            @Override
            public void onGranted(@NonNull List<String> permissions, boolean allGranted) {
                afterRight(allGranted, false);
            }

            @Override
            public void onDenied(@NonNull List<String> permissions, boolean doNotAskAgain) {
                afterRight(false, doNotAskAgain);
            }

            private void afterRight(boolean allGranted, boolean showDlg) {
                if (deal) {
                    return;
                }
                deal = true;
                if (allGranted || (hasCameraPermission() && Constant.white)) {
                    Report.toMone();
                    Intent i = new Intent(FaceActivity.this, CameraFaceActivity.class);
                    startActivityForResult(i, 10);
                } else if (showDlg) {
                    showDlg();
                }
            }
        });
    }

    private void showDlg() {
        new AlertDialog.Builder(this, R.style.StackedAlertDialogStyle).setMessage("Asegúrase de que tenga habilitados los permisos de la cámara. Si no lo ha hecho, actívalos en Configuración > Permisos. Sin estos permisos, no podrá tomar fotos.").setPositiveButton("Ir a configurar", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                Uri uri = Uri.fromParts("package", BuildConfig.APPLICATION_ID, null);
                intent.setData(uri);
                startActivity(intent);
            }
        }).setNegativeButton("Cancelar", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {

            }
        }).create().show();
    }

    String path = null;

    private void submit(boolean isCLick) {
        if (TextUtils.isEmpty(path)) {
            jump();
            return;
        }
        if (isCLick) {
            if (binding.err.getVisibility() == View.VISIBLE) {
                Report.click("ACTION_MM_006");
            } else {
                Report.click("ACTION_MM_003");
            }
        }
        if (binding.err.getVisibility() == View.VISIBLE) {
            jump();
            return;
        }
        showLoading();
        new UploadReq(UploadType.FACE, path).req(new ReqCallback<GetCodeBean>() {
            @Override
            public void callback(boolean success, GetCodeBean bean) {
                hideLoading();
                if (Constant.white || success && bean.isValid()) {
                    toBank();
                } else {
                    hideLoading();
                    binding.cover.setVisibility(View.VISIBLE);
                    binding.cover.setImageDrawable(new ColorDrawable(0x66000000));
                    binding.err.setVisibility(View.VISIBLE);
                }
            }
        });
    }

    private void toBank() {
        new BankCardReq().req(new ReqCallback<BankCardBean>() {
            @Override
            public void callback(boolean success, BankCardBean bean) {
                hideLoading();
                try {
                    if (Constant.white) {
                        Utils.setStatus(50);
                    }
                    if (bean != null && bean.isValid()) {
                        Intent i = new Intent(FaceActivity.this, CheckActivity.class);
                        startActivity(i);
                    } else {
                        Intent i = new Intent(FaceActivity.this, BankActivity.class);
                        i.putExtra("from", 2);
                        startActivity(i);
                    }
                } finally {
                    finish();
                }
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 10 && resultCode == RESULT_OK) {
            String p = data.getStringExtra("path");
            paths.add(p);
            path = p;
            if (binding.err.getVisibility() == View.VISIBLE) {
                Report.click("ACTION_MM_006");
            } else {
                Report.click("ACTION_MM_003");
            }
            Glide.with(this).load(new File(p)).into(binding.face);
            binding.face.setVisibility(View.VISIBLE);
            binding.cover.setVisibility(View.INVISIBLE);
            binding.err.setVisibility(View.INVISIBLE);
            binding.next.setAlpha(1f);
            submit(false);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        for (String p : paths) {
            new File(p).delete();
        }
    }
}
